package com.scshyzh.redis.lock;

import lombok.Getter;

import java.io.Serializable;
import java.util.concurrent.TimeUnit;

/**
 * @author: songkui
 * @since: 2022/6/28 10:55
 */
public class MochaRedissonLock<T> implements Serializable {

    protected String lockKey;  //锁key 尽量细粒度
    protected int waitTime;   //waitTime 未获取到锁，则返回null
    protected int leaseTime;  // if leaseTime != -1 执行方法时间超过 leaseTime 则自动释放锁； else : 不超时；启动看门狗自动加 leaseTime三分之一时间；
    protected TimeUnit unit;

    protected T t;  // 传入参数

    public MochaRedissonLock(String lockKey, int waitTime, int leaseTime, TimeUnit timeUnit, T t){
        this.lockKey = lockKey;
        this.waitTime = waitTime;
        this.leaseTime = leaseTime;
        this.unit = timeUnit;
        this.t = t;
    }

    public static  <T> MochaRedissonLock<T> of(String lockKey, int waitTime, int leaseTime, TimeUnit timeUnit, T t){
        return new MochaRedissonLock(lockKey, waitTime, leaseTime, timeUnit, t);
    }

    public static  <T> MochaRedissonLock<T> of(String lockKey,  T t){
        return of(lockKey, -1, -1, null, t);
    }


    public static  <T> MochaRedissonLock<T> ofLease(String lockKey, int leaseTime, TimeUnit timeUnit, T t){
        return of(lockKey, -1, leaseTime, timeUnit, t);
    }

    public static  <T> MochaRedissonLock<T> ofWait(String lockKey, int waitTime, TimeUnit timeUnit, T t){
        return of(lockKey, waitTime, -1, timeUnit, t);
    }


    /**
     * code:  200 表示成功
     * @param <R>
     */
    public static class RedisLockResult<R> implements Serializable{
        @Getter
        protected int code;
        @Getter
        protected String msg;
        @Getter
        protected R rd;

        public RedisLockResult(){}

         public RedisLockResult(int code, String msg, R rd){
            this.code = code;
            this.msg = msg;
            this.rd = rd;
         }

         public static <R> RedisLockResult<R> of(int code, String msg, R rd){
            return new RedisLockResult(code, msg, rd);
         }
         public static <R> RedisLockResult<R> of(int code, String msg){
            return of(code, msg, null);
         }

         public static <R> RedisLockResult of(R rd){
            return of(200, "SUCCESS", rd);
         }

         public boolean isSuccess(){
             return 200 == this.code ? true : false;
         }
    }



}
